package com.bootdo.common.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.UUID;

public class FileUtil {
	private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

	public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
		File targetFile = new File(filePath);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream out = new FileOutputStream(filePath + fileName);
		out.write(file);
		out.flush();
		out.close();
	}

	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	public static String renameToUUID(String fileName) {
		return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
	}

	public static String upload(MultipartFile file, String uploadPath, String id) throws Exception {
		// 日期，用于按日生成文件夹
		String dateStr = DateFormatUtils.format(new Date(), "yyyyMMdd");
		// 文件名
		String originalFilename = file.getOriginalFilename();
		String filename = id + originalFilename.substring(originalFilename.lastIndexOf("."));

		// 文件保存位置
		String url = "/" + dateStr + "/" + filename;
		// 请求URL路径 +文件保存位置
		String filePath = uploadPath + url;
		logger.info("图片上传的地址：filePath" + filePath);
		File file2 = new File(filePath);
		FileUtils.copyInputStreamToFile(file.getInputStream(), file2);
		return url;
	}
}
